<template>
  <div class="container">
    <Breadcrumb />
    <a-card class="data-card" v-if="!usershow">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
          >
            <a-row :gutter="20">
              <a-col :span="5">
                <a-form-item field="username" label="账号">
                  <a-input
                    v-model="formModel.username"
                    placeholder="请输入用户名"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="5">
                <a-form-item field="nickname" label="姓名">
                  <a-input
                    v-model="formModel.nickname"
                    placeholder="请输入姓名"
                    allow-clear
                  />
                </a-form-item>
              </a-col>

              <a-col :span="5">
                <a-form-item field="userType" label="用户类型">
                  <a-select
                    v-model="formModel.userType"
                    placeholder="请选择用户类型"
                    ><a-option
                      v-for="item of userTypes"
                      :key="item.id"
                      :value="item.id"
                      >{{ item.name }}</a-option
                    >
                  </a-select>
                </a-form-item>
              </a-col>

              <a-col :span="5">
                <a-space :size="18">
                  <a-button type="primary" @click="onPageChange(1)">
                    <template #icon>
                      <icon-search />
                    </template>
                    搜索
                  </a-button>
                  <a-button @click="reset">
                    <template #icon>
                      <icon-refresh />
                    </template>
                    重置
                  </a-button>
                </a-space>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />

      <a-table
        ref="userList"
        row-key="userId"
        v-model:selectedKeys="userIds"
        :loading="loading"
        page-position="bottom"
        :pagination="pagination"
        :columns="columns"
        :data="renderData"
        :bordered="false"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #sex="{ record }">
          <template v-for="(item, index) in sexs">
            <span v-if="record.sex == item.value">{{ item.label }}</span>
          </template>
        </template>

        <template #userType="{ record }">
          {{ getAppointmentTypes(record.userType) }}
        </template>

        <template #option="{ record }">
          <a-space :size="18">
            <a-button @click="openEdit(record)" type="primary">
              查看详情
            </a-button>
            <a-button type="outline" @click="openRePass(record)">
              恢复满分
            </a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>
    <a-modal
      v-model:visible="addShow"
      @cancel="handleCancel"
      :on-before-ok="handleCheck"
      :mask-closable="false"
      unmountOnClose
      width="450px"
    >
      <template #title> 恢复满分 </template>
      <a-form ref="addModel" :rules="rules" :model="addForm">
        <a-row class="hfmfdiv">
          <div class="hfmitem">用户名称：{{ hfdata.nickname }}</div>
          <div class="hfmitem">信用分：{{ hfdata.userCredit }}</div>
          <div class="hfmitem"
            >用户类型：{{ getAppointmentTypes(hfdata.userType) }}</div
          >
        </a-row>
        <a-row>
          <a-col>
            <a-form-item field="" label="备注">
              <a-textarea
                placeholder="请您写明恢复该用户满分的原因"
                allow-clear
                v-model="hfdata.remark"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>

    <a-card title="用户基本信息" v-if="usershow">
      <a-form ref="addModel" :model="addForm" class="fzzt">
        <a-row :gutter="10">
          <a-col :span="10">
            <a-form-item field="title" label="工号/学号:">
              {{ addForm.username }}</a-form-item
            >
            <a-form-item field="title" label="用户姓名:">
              {{ addForm.nickname }}</a-form-item
            >
            <a-form-item field="title" label="用户来源:">
              {{ addForm.createUser }}</a-form-item
            >
          </a-col>
          <a-col :span="10">
            <a-form-item field="title" label="班级:">
              {{ addForm.organizationName }}</a-form-item
            >
            <a-form-item field="title" label="手机号:">
              {{ addForm.mobile }}</a-form-item
            >
            <a-form-item field="title" label="预约记录:">
              {{ addForm.appointmentNumber }}</a-form-item
            >
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card title="信用分变化记录" style="margin-top: 20px" v-if="usershow">
      <a-timeline>
        <div class="divTable">
          <div class="rows">
            <div class="cell">增减变化</div>
            <div class="cell">信用分变化</div>
            <div class="cell">行为详情 </div>
            <div class="cell">发生时间 </div>
          </div>
          <div
            class="row"
            v-for="item in creditlist"
            v-if="creditlist.length > 0"
          >
            <div class="cells" v-if="item.scoreType != 'ADD'">
              <a-timeline-item> -{{ item.score }}分</a-timeline-item></div
            >
            <div class="cell" v-if="item.scoreType != 'ADD'"
              >信用分余额{{ item.balance }}分</div
            >
            <div class="cell" v-if="item.scoreType != 'ADD'">{{
              item.cause
            }}</div>
            <div class="cell" v-if="item.scoreType != 'ADD'">{{
              item.createTime
            }}</div>
          </div>
          <div v-else class="rowdd"> 暂无数据 </div>
        </div></a-timeline
      >
      <!-- <div class="backf">
        <a-button @click="backfn" type="primary"> 返回 </a-button>
      </div> -->
    </a-card>
    <a-card title="恢复信用分记录" style="margin-top: 20px" v-if="usershow">
      <a-timeline>
        <div class="divTable">
          <div class="rows">
            <div class="cell">增减变化</div>
            <div class="cell">操作人员</div>
            <div class="cell">行为详情 </div>
            <div class="cell">发生时间 </div>
          </div>
          <div
            class="row"
            v-for="item in creditlist"
            v-if="creditlist.length > 0"
          >
            <div class="cells" v-if="item.scoreType == 'ADD'">
              {{ item.balance }}分</div
            >
            <div class="cell" v-if="item.scoreType == 'ADD'">{{
              item.createUser
            }}</div>
            <div class="cell" v-if="item.scoreType == 'ADD'">{{
              item.cause
            }}</div>
            <div class="cell" v-if="item.scoreType == 'ADD'">{{
              item.createTime
            }}</div>
          </div>
          <div v-else class="rowdd"> 暂无数据 </div>
        </div></a-timeline
      >
    </a-card>
    <div class="backf" v-if="usershow">
      <a-button @click="backfn" type="primary"> 返回 </a-button>
    </div>
  </div>
</template>
<script lang="ts">
  export default {
    name: 'user',
  };
</script>
<script lang="ts" setup>
  import { computed, ref, reactive } from 'vue';
  import useLoading from '@/hooks/loading';
  import { useSelectionStore } from '@/store';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import { Message, Modal } from '@arco-design/web-vue';

  import {
    downloadTemplate,
    creditList,
    importUser,
    userListd,
    UserSave,
    UserUpdate,
    resetCredit,
    appointmentNumber,
  } from '@/api/creditlist';

  // import { majorTree } from '@/api/major.ts';

  const { loading, setLoading } = useLoading(true);
  const usershow = ref(false);
  const generateDataModel = () => {
    return {
      userId: '',
      username: '',
      nickname: '',
      password: '',
      sex: '',
      mobile: '',
      deptId: '',

      effectiveTime: '',
      organizationList: [],
      organizationId: '',
      // majorIdsArr: [],
    };
  };
  // 返回
  const backfn = () => {
    usershow.value = false;
    creditlist.value = [];
    reset();
  };
  const rules = reactive({
    username: [
      {
        required: true,
        message: '请输入用户名',
      },
      {
        minLength: 4,
        message: '最少输入四位',
      },
    ],
    password: [
      {
        required: true,
        message: '请输入密码',
      },
      {
        minLength: 4,
        message: '最少输入四位',
      },
    ],
    nickname: [
      {
        required: true,
        message: '请输入姓名',
      },
    ],
    sex: [
      {
        required: true,
        message: '请选择性别',
      },
    ],
    userType: [
      {
        required: true,
        message: '请选择性别',
      },
    ],
  });
  const addForm = ref(generateDataModel());
  const addShow = ref(false);
  const addModel = ref();
  const hfdata = ref([]);
  // const openAdd = () => {
  //   rules.password[0].required = true;
  //   rules.username[0].required = true;
  //   rules.sex[0].required = true;
  //   addForm.value = generateDataModel();
  //   addShow.value = true;
  // };

  const handleCheck = (done) => {
    // if (loading.value) {
    //   done(false);
    //   return;
    // }

    resetCredit({
      userId: hfdata.value.userId,
      remark: hfdata.value.remark,
    }).then((res) => {
      if (res.code == '200') {
        Message.success({
          //   content: res.message,
          content: '恢复成功',
        });
        addShow.value = false;
        fetchData();
      }
    });
  };

  const creditlist = ref([]);
  const openEdit = (item) => {
    // rules.password[0].required = false;
    // rules.username[0].required = false;
    // rules.sex[0].required = false;
    // let majorIdsArr = [];
    // if (item.majorIds) {
    //   majorIdsArr = item.majorIds.split(',');
    //   majorIdsArr = majorIdsArr.map((item) => {
    //     return +item;
    //   });
    // }
    addForm.value = Object.assign({}, item, {});
    appointmentNumber({
      userId: item.userId,
    }).then((res) => {
      addForm.value.appointmentNumber = res.data;
    });
    creditList({
      userId: item.userId,
    }).then((res) => {
      console.log('当前扣分详细记录', res);

      creditlist.value = res.data;
    });
    usershow.value = true;

    // console.log('ss', rules.username[0].required);
  };

  const handleCancel = () => {
    addShow.value = false;
  };

  const openRePass = (item) => {
    if (item.userCredit < 100) {
      hfdata.value = item;
      console.log('当前用户信息', hfdata.value);

      addShow.value = true;
    } else {
      Modal.confirm({
        title: '提示',
        content: '当前用户信用分已经是满分！',
        onOk() {
          // resetCredit({
          //   userId: item.userId,
          // }).then((res) => {
          //   if (res.code == '200') {
          //     Message.success({
          //       //   content: res.message,
          //       content: '恢复成功',
          //     });
          //   }
          // });
        },
      });
    }
  };

  const generateLockModel = () => {
    return {
      userIds: '',
    };
  };
  const lockForm = ref(generateLockModel());

  const lockShow = ref(false);
  const userIds = ref([]);

  const openUnlock = (item) => {
    lockForm.value = {
      ...generateLockModel(),
      userIds: item.userId,
    };
    lockShow.value = true;
  };

  const generateUploadModel = () => {
    return {
      file: null,
      userType: '',
      organizationId: '',
    };
  };

  const uploadRules = {
    file: [
      {
        required: true,
        message: '请选择附件',
      },
    ],
    userType: [
      {
        required: true,
        message: '请选择用户类型',
      },
    ],
  };
  const uploadForm = ref(generateUploadModel());
  const uploadShow = ref(false);
  const uploadModel = ref();
  // const openUpload = () => {
  //   uploadForm.value = generateDataModel();
  //   uploadShow.value = true;
  // };

  const onChange = (fileList) => {
    if (fileList && fileList.length > 0) {
      uploadForm.value.file = fileList[0].file;
    } else {
      uploadForm.value.file = null;
    }
  };

  const uploadCheck = (done) => {
    if (loading.value) {
      done(false);
      return;
    }
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1500);
    uploadModel.value.validate(
      async (errors: undefined | Record<string, ValidatedError>) => {
        if (!errors) {
          let formData = new FormData();
          formData.append('organizationId', uploadForm.value.organizationId);
          formData.append('userType', uploadForm.value.userType);

          formData.append('file', uploadForm.value.file);
          importUser(formData).then((res) => {
            if (res.code == '200') {
              Message.success({
                content: res.message,
              });
              reset();
              done(true);
            } else {
              done(false);
            }
          });
        } else {
          done(false);
        }
      }
    );
  };
  const uploadCancel = () => {
    uploadShow.value = false;
  };

  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });
  const userTypes = reactive([
    { id: 'TEACHER', name: '老师' },
    { id: 'STUDENT', name: '学生' },
    { id: 'VISITOR', name: '访客' },
  ]);
  const columns = computed<TableColumnData[]>(() => [
    {
      title: '账号',
      dataIndex: 'username',
    },
    {
      title: '姓名',
      dataIndex: 'nickname',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      slotName: 'sex',
      align: 'center',
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      align: 'center',
    },

    {
      title: '用户类型',
      dataIndex: 'userType',
      align: 'center',
      slotName: 'userType',
    },
    {
      title: '班级ID',
      dataIndex: 'organizationId',
      align: 'center',
    },
    {
      title: '班级名称',
      dataIndex: 'organizationName',
      align: 'center',
    },
    {
      title: '信用分',
      dataIndex: 'userCredit',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'option',
      slotName: 'option',
      align: 'center',
    },
  ]);

  const sexs = useSelectionStore().sexs;

  const generateFormModel = () => {
    return {
      username: '',
      nickname: '',
      sex: '',
      userType: '',
    };
  };

  const formModel = ref(generateFormModel());
  const renderData = ref([]);
  const userList = ref();

  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    total: 0,
  };
  // const pagination = reactive({
  //   ...basePagination,
  //   'hide-on-single-page': true,
  //   'show-total': true,
  //   'show-jumper': true,
  //   'show-page-size': true,
  // });
  const pagination = ref({
    ...basePagination,
    'hide-on-single-page': true,
    'show-total': true,
    'show-jumper': true,
    'show-page-size': true,
  });

  const fetchData = async () => {
    setLoading(true);
    try {
      const data = {
        pageNum: pagination.value.current,
        ...pagination.value,
        ...formModel.value,
      };
      userListd(data).then((res) => {
        let list = res.data.list || [];
        list.map((item) => {
          item.disabled = item.isLocking == 1 ? false : true;
        });
        renderData.value = list;
        pagination.value.total = res.data.total;
        pagination.value.current = res.data.pageNum;

        userList.value.selectAll(false);
      });
    } catch (err) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };

  const onPageChange = (current: number) => {
    pagination.value.current = current;
    fetchData();
  };
  const onPageSizeChange = (pageSize: number) => {
    pagination.value.pageSize = pageSize;
    fetchData();
  };

  const reset = () => {
    pagination.value.current = 1;
    formModel.value = generateFormModel();
    fetchData();
  };

  // const downloadUser = () => {
  //   adminUserExport(formModel.value).then((res) => {});
  // };

  const rolesFields = {
    value: 'roleId',
    label: 'roleName',
  };

  const getAppointmentTypes = (openAppointment: string) => {
    const types = openAppointment.split(','); // 将字符串按逗号分割成数组
    return types.map((type: string) => getAppointmentType(type)).join(', '); // 调用 getAppointmentType 转换为中文后再连接成字符串
  };
  const getAppointmentType = (type: string): string => {
    switch (type) {
      case 'TEACHER':
        return '老师';
      case 'STUDENT':
        return '学生';
      case 'VISITOR':
        return '访客';
      default:
        return '';
    }
  };
  fetchData();
</script>
<style>
  .divTable {
    display: flex;
    flex-direction: column;
    max-height: 400px;
    /* background-color: red; */
    overflow-y: auto;
  }
  .row {
    display: flex;
  }
  .rows {
    display: flex;
    font-size: 18px;
    text-align: center;
  }
  .cell {
    text-align: center;
    width: 400px;
    height: 30px;
    font-size: 17px;
  }
  .cells {
    width: 400px;
    padding-left: 170px;
  }
  .divTable .arco-timeline-item {
    min-height: 30px;
  }
  .backf {
    text-align: center;
    margin: 20px 0;
  }
  .rowdd {
    font-size: 16px;
    text-align: center;
    margin: 20px 0;
  }
  .fzzt {
    font-size: 18px;
    max-width: 0 auto;
    padding-left: 100px;
  }
  .fzzt .arco-form-item-label-col {
    /* text-align: right !important;
    width: 600px !important;
    background-color: red; */
  }
  .fzzt .arco-form-item-label {
    font-size: 18px;
  }
  .hfmfdiv {
    display: flex;
    align-content: center;
    font-size: 14px;
    color: #4e5969;
    margin-bottom: 20px;
    margin-left: 20px;
  }
  .hfmitem {
    margin: 0px 10px;
  }
</style>
